package com.zwz.service.impl;
import com.zwz.entity.EnterpriseInfo;
import com.zwz.entity.OfficialWebsiteInfo;
import com.zwz.mapper.OfficialWebsiteInfoMapper;
import com.zwz.service.OfficialWebsiteInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
@Transactional
public class OfficialWebsiteInfoServiceImpl implements OfficialWebsiteInfoService {

    @Autowired
    private OfficialWebsiteInfoMapper mapper;

    @Override
    public void create(OfficialWebsiteInfo record) {
        //
        // 创建主表记录
        EnterpriseInfo enterpriseInfo=new EnterpriseInfo();
        enterpriseInfo.setId(Long.valueOf(record.getEnterpriseId()));

        record.setEnterpriseId(Math.toIntExact(enterpriseInfo.getId()));
        validateIcpConsistency(record);
        mapper.insert(record);
    }

    @Override
    public void update(OfficialWebsiteInfo record) {
        validateIcpConsistency(record);
        mapper.update(record);
    }

    @Override
    public void delete(Integer id) {
        mapper.deleteById(id);
    }

    @Override
    public OfficialWebsiteInfo getById(Integer id) {
        return mapper.selectById(id);
    }

    @Override
    public List<OfficialWebsiteInfo> getByIcpStatus(Boolean hasIcp) {
        return mapper.selectByIcpStatus(hasIcp);
    }

    @Override
    public OfficialWebsiteInfo getByUrl(String url) {
        return mapper.selectByUrl(url);
    }

    // 校验ICP备案逻辑一致性
    private void validateIcpConsistency(OfficialWebsiteInfo record) {
        if (record.getHasIcpRecord() && record.getIcpRecordCount() <= 0) {
            throw new IllegalArgumentException("有备案时备案数量必须大于0");
        }
        if (!record.getHasIcpRecord() && record.getIcpRecordCount() > 0) {
            throw new IllegalArgumentException("无备案时备案数量必须为0");
        }

        //处理垃圾数据
        if (StringUtils.isEmpty(record.getWebsiteUrl())) {
          //调用预先处理的方法
            record.setWebsiteUrl("无");
        }


    }
}